<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\template\instructions;

interface IInclude
{
}

class ContainerInclude extends Base implements IInclude, IConcrete
{
  public function execute()
  {
    $sFile = $this->getAttribute('include');

    $oTemplate = \crcl\base\Template::fromFile($sFile);


    $aValues = array();

    foreach ($this->aAttributes as $sAttribute => $value)
    {
      if (\strpos($sAttribute, 'define:') === 0)
      {
        if (\strlen($sAttribute) == 7)
        {
          throw new Exception('Missing defined var',
            Exception::ERROR_INCLUDE_MISSINGDEFINEDVAR,
            array('sAttribute' => $sAttribute));
        }
        $sContent = \substr($sAttribute, 7); //define: weg
        $aValues[$sContent] = $value;
      }
    }
    $oTemplate->setValues($aValues);

    $this->sOutput = $oTemplate->executeAsString();
  }

  public function verify()
  {
    $sFile = $this->getAttribute('include');
    if (\strpos($sFile, '..') !== \FALSE)
    {
      throw new Exception('Illegal path',
        Exception::ERROR_INCLUDE_ILLEGALPATH, array('sFile' => $sFile));
    }

    $bReturn = parent::verify();
    return $bReturn;
  }

  /** PRIVATE *************************************************************************************/

  protected $aAllowedAttributes = array('include', 'define');

  private function getFileContent($sFile)
  {
    $sFile =
      \crcl\base\application\Path::getDirectory(
        \crcl\base\application\Path::DIR_TEMPLATES) . $sFile;

    $sContent = @\file_get_contents($sFile);
    if ($sContent === \FALSE)
    {
      throw new Exception('File is missing',
        Exception::ERROR_INCLUDE_MISSINGFILE, array('file' => $sFile));
    }
    return $sContent;
  }
}